package com.zhu.tool_test.mock.comparison;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.util.MultiValueMap;

import java.io.UnsupportedEncodingException;

/**
 * @program: tool_test
 * @description:
 * @author: ggBall
 * @create: 2020-12-26 17:43
 **/
@Slf4j
public class GgToolMockMvcFactory {

    private MockMvc mockMvc;

    private ResultActions resultActions;

    public GgToolMockMvcFactory() {
    }

    public GgToolMockMvcFactory(Object ... objs){
        mockMvc = MockMvcBuilders.standaloneSetup(objs).build();
    }

    /**
     * 根据url 构建请求
     * @param url
     */
    public GgToolMockMvcFactory buildPerform(String url,MultiValueMap multiValueMap){

        // 设置url
        try {
             resultActions = mockMvc.perform(MockMvcRequestBuilders
                    .get(url)
                     .params(multiValueMap)
                    .characterEncoding("UTF-8")
                    // 设置返回值类型为utf-8，否则默认为ISO-8859-1
                    .accept(MediaType.APPLICATION_JSON_VALUE));

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        // 设置返回值utf-8
        try {
            resultActions
                    .andExpect(MockMvcResultMatchers.status().isOk())
                    .andReturn()
                    .getResponse()
                    .setCharacterEncoding("UTF-8");
            return this;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 返回接口结果内容
     * @return
     */
    public String getContent(){
        try {
            String contentAsString = resultActions
                    .andDo(MockMvcResultHandlers.print())
                    .andReturn()
                    .getResponse()
                    .getContentAsString();
            return contentAsString;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return e.getMessage();
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    public <T> T getJavaType(Class<T> tClass) {

        try {
            JSONObject jsonObject = JSONObject.parseObject(getContent());
            T t = jsonObject.toJavaObject(tClass);
            return t;
        }catch (Exception e) {
            e.printStackTrace();
            return null;
        }


    }
}
